<template>
  <tn-popup
    v-model="showPopup"
    :mask="mask"
    mode="center"
    :z-index="zIndex"
    :content-custom-style="{background: 'transparent'}"
    close-icon=""
  >
    <view class="tn-toast">
      <view v-if="icon" class="tn-toast__icon">
        <tn-icon :icon="icon" :size="64"></tn-icon>
      </view>
      <view v-if="title" class="tn-toast__title">
        {{ title }}
      </view>
    </view>
  </tn-popup>
</template>

<script lang="ts" setup>
import { ToastOption, toastProps, toastEmits } from '../../../types/tn-toast'
import { ref } from 'vue'
import TnIcon from '../../tn-icon/src/Icon.vue'
import TnPopup from '../../tn-popup/src/Popup.vue'

const props = defineProps(toastProps)
const emits = defineEmits(toastEmits)

// 弹出toast
let showPopup = ref<boolean>(false)
// 显示的图标
let icon = ref<string>('')
// 显示的文本信息
let title = ref<string>('')
// 关闭定时器
let timer: number | null

// 弹出toast显示框
const show = (option: ToastOption) => {
  // 如果没有内容则直接返回
  if (!option?.title && !option?.icon) {
    resetToastInfo()
    return
  }
  resetTimer()
  let duration = option?.duration || 2000

  title.value = option?.title || ''
  icon.value = option.icon || ''
  showPopup.value = true

  timer = setTimeout(() => {
    showPopup.value = false
    resetToastInfo()
    resetTimer()
    emits('close')
  }, duration);
}

// 重置定时器
const resetTimer = () => {
  if (timer) {
    clearTimeout(timer)
    timer = null
  }
}
// 重置显示信息
const resetToastInfo = () => {
  showPopup.value = false
  icon.value = ''
  title.value = ''
}

defineExpose({
  show
})
</script>

<script lang="ts">
export default {
  options: {
    // 在微信小程序中将组件节点渲染为虚拟节点，更加接近Vue组件的表现(不会出现shadow节点下再去创建元素)
    virtualHost: true
  }
}
</script>

<style lang="scss" scoped>
.tn-toast {
  background-color: rgba(0, 0, 0, 0.5);
  color: #FFFFFF;
  border-radius: 10rpx;
  padding: 18rpx 28rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  &__icon {
    line-height: 1;
    margin-bottom: 4rpx;
  }
}
</style>
